import { defineConfig, loadEnv, type ConfigEnv, type UserConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { resolve } from 'path'
import { wrapperEnv } from './src/utils/handleEnv'
import eslintPlugin from 'vite-plugin-eslint'
import viteCompression from 'vite-plugin-compression'
// import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig((mode: ConfigEnv): UserConfig => {
  const env = loadEnv(mode.mode, process.cwd())
  const viteEnv = wrapperEnv(env)
  return {
    resolve: {
      alias: {
        '@': resolve(__dirname, './src'),
      },
    },
    server: {
      port: viteEnv.VITE_PORT,
      cors: true,
      proxy: {
        // zejun
        // '/api/sop': {
        //   target: 'http://10.2.1.34:8080/',
        //   changeOrigin: true,
        //   rewrite: (path) => path.replace('/api/sop', ''),
        // },
        // '/api/auth': {
        //   target: 'http://10.2.1.34:9902/',
        //   changeOrigin: true,
        //   rewrite: (path) => path.replace('/api/auth', ''),
        // },
        //wangtao
        // '/api/sop': {
        //   target: 'http://10.2.1.52:8080/',
        //   changeOrigin: true,
        //   rewrite: (path) => path.replace('/api/sop', ''),
        // },
        // '/api/auth': {
        //   target: 'http://10.2.1.52:9902/',
        //   changeOrigin: true,
        //   rewrite: (path) => path.replace('/api/auth', ''),
        // },
        // zhijiang
        // '/sop': {
        //   target: 'http://10.2.1.55:9903/',
        //   changeOrigin: true,
        // },
        //开发环境
        // '/api': {
        //   target: 'http://10.0.1.93:7777/',
        //   changeOrigin: true,
        // },
        //测试环境
        '/api': {
          target: 'https://soptest.7sef.com/',
          changeOrigin: true,
        },
      },
    },
    css: {
      preprocessorOptions: {
        less: {
          javascriptEnabled: true,
        },
      },
    },
    plugins: [
      // visualizer({
      //   open: true,
      //   gzipSize: true,
      //   brotliSize: true,
      // }) as any,
      react(),
      eslintPlugin({ fix: true }),
      // * gzip compress
      viteEnv.VITE_BUILD_GZIP &&
        viteCompression({
          verbose: true,
          disable: false,
          threshold: 10240,
          algorithm: 'gzip',
          ext: '.gz',
        }),
    ],
    esbuild: {
      pure: viteEnv.VITE_DROP_CONSOLE ? ['console.log', 'debugger'] : [],
    },
    build: {
      outDir: 'build',
      minify: 'esbuild',
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
        },
      },
    },
  }
})
